package Exams.TianChi;

import java.util.Arrays;

public class q3 {
    public int chickenCoolRun(int[][] paths) {
        final int INF = Integer.MAX_VALUE / 2;
        int n = paths[0].length;
        int[] dp = new int[3];
        Arrays.fill(dp, INF);
        dp[1] = 0;
        if (paths[0][0] == 0) {
            dp[0] = 1;
        }
        if (paths[2][0] == 0) {
            dp[2] = 1;
        }
        for (int j = 1; j < n; j++) {
            int[] dpNew = new int[3];
            Arrays.fill(dpNew, INF);
            for (int i = 0; i < 3; i++) {
                if (dp[i] < INF && paths[i][j] == 0) {
                    dpNew[i] = dp[i];
                }
            }
            dp = dpNew;
            if (paths[1][j] == 1) {
                continue;
            }
            if (dp[0] < INF) {
                dp[1] = Math.min(dp[1], dp[0] + 1);
            }
            if (dp[2] < INF) {
                dp[1] = Math.min(dp[1], dp[2] + 1);
            }
            if (paths[0][j] == 0) {
                dp[0] = Math.min(dp[0], dp[1] + 1);
            }
            if (paths[2][j] == 0) {
                dp[2] = Math.min(dp[2], dp[1] + 1);
            }
        }
        int minChanges = Math.min(Math.min(dp[0], dp[1]), dp[2]);
        return minChanges < INF ? minChanges : -1;
    }
}
